<!-- EllipsisTooltip.vue -->
<template>
  <el-tooltip v-if="showTooltip" placement="top" effect="dark">
    <template #content>
      <div class="whitespace-pre-line break-words" :style="{ maxWidth: tooltipWidth + 'px' }">
        {{ content }}
      </div>
    </template>
    <div
      ref="textRef"
      class="w-full"
      :class="{
        'truncate text-base': !byRow, // 单行模式
        'multiline-ellipsis': byRow, // 多行模式
      }"
      :style="byRow ? { WebkitLineClamp: row } : {}"
    >
      <slot />
    </div>
  </el-tooltip>

  <div
    v-else
    ref="textRef"
    class="w-full"
    :class="{
      'truncate text-base': !byRow,
      'multiline-ellipsis': byRow,
    }"
    :style="byRow ? { WebkitLineClamp: row } : {}"
  >
    <slot />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, watch, nextTick } from 'vue'

  const props = defineProps<{
    content: string
    row?: number
    byRow?: boolean
    tooltipWidth?: number // 新增：tooltip 最大宽度
  }>()

  const textRef = ref<HTMLElement | null>(null)
  const showTooltip = ref(false)

  const checkOverflow = () => {
    if (!textRef.value) return
    const el = textRef.value

    if (props.byRow && props.row && props.row > 1) {
      // 多行截断
      const lineHeight = parseFloat(getComputedStyle(el).lineHeight || '0')
      const maxHeight = lineHeight * props.row
      showTooltip.value = el.scrollHeight > maxHeight + 1
    } else {
      // 单行截断
      showTooltip.value = el.scrollWidth > el.clientWidth
    }
  }

  onMounted(() => {
    nextTick(() => checkOverflow())
  })

  watch(
    () => props.content,
    async () => {
      await nextTick()
      checkOverflow()
    }
  )
</script>

<style scoped>
  .multiline-ellipsis {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
</style>
